package demo1;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Date: 2023-06-10
 * Time: 11:37
 */
public class MyArrayList {
    public int[] elem;
    public int useSize;
    public static final int DEFULT_SIZE = 10;

    public MyArrayList(){
        this.elem = new int[DEFULT_SIZE];
    }

    public void display(){
        for (int i = 0; i < this.useSize; i++) {
            System.out.print(this.elem[i] + " ");
        }
        System.out.println();
    }

    public int size(){
        return this.useSize;
    }

    public boolean contains (int toFind){
        for (int i = 0; i < this.useSize; i++) {
            if(this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }

    public int indexOf(int toFind){
        for (int i = 0; i < this.useSize; i++) {
            if(this.elem[i] == toFind){
                return i;
            }
        }
        return -1;
    }

    public boolean isFull(){
       /*if(this.useSize == this.elem.length) {
           return true;
       }
       return false;*/
        return this.useSize == this.elem.length;
    }
    private  void resize(){
        this.elem = Arrays.copyOf(this.elem,
                2*this.elem.length);
    }

    public void add(int data){
        if (this.isFull()) {
            resize();
        }
        this.elem[this.useSize] = data;
        this.useSize++;
    }

    private void checkIndex(int pos){
        if(pos < 0 || pos > useSize){
            throw new IndexOutOfException("位置不合法,请检查位置的合法性");
        }
    }
    public void add(int pos,int data){
        checkIndex(pos);
        if (this.isFull()) {
            resize();;
        }
        for (int i = useSize-1; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.useSize++;
    }
    private void checkGetIndex(int pos){
        if(pos < 0 || pos >= useSize){
            throw new IndexOutOfException("get获取元素的时候位置不合法,请检查位置的合法性");
        }
    }
    public int get(int pos){
        checkGetIndex(pos);
        return this.elem[pos];
    }

    public void set(int pos,int valuse){
        checkIndex(pos);
        this.elem[pos] = valuse;
    }

    public boolean remove(int toRemove){
        int index = indexOf(toRemove);
        if(index == -1){
            System.out.println("没有这个数据");
            return false;
        }
        for (int i = index; i < this.useSize-1; i++) {
            this.elem[i] = this.elem[i+1];
        }
        useSize--;
        this.elem[useSize] = 0;
        return true;
    }

    public void clear(){
        useSize = 0;
    }
}













































